package com.deyuanyun.pic.web.interceptor;


import com.deyuanyun.pic.common.exception.AssertsException;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;

/**
 * 异常拦截
 */
public class ExceptionInterceptor extends HandlerInterceptorAdapter {
    //static Logger log= Logger.getLogger(ExceptionInterceptor.class);
    static Logger log = LogManager.getLogger(ExceptionInterceptor.class);
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        if(ex!=null){
            logger(request, handler, ex);
            response.setStatus(response.SC_SERVICE_UNAVAILABLE);
            String m="";
            if(DataAccessException.class.isAssignableFrom(ex.getClass())
                    || SQLException.class.isAssignableFrom(ex.getClass())){//如果是数据库访问的出错
                m="数据库查询出错了！请联系客服。";
            }else if (ex instanceof AssertsException){ //如果是断言异常，直接返回到页面
                AjaxSupport.sendFailText("assert",ex.getMessage());
                return;
            }
            else {
                m=ex.getMessage();
            }
            List<String> ajaxMode = SessionVOInterceptor.getParmByName(request.getParameterMap(), "AjaxMode", null);
            List<String> uploadFile = SessionVOInterceptor.getParmByName(request.getParameterMap(), "uploadFile", null);
            if (ajaxMode==null || ajaxMode.isEmpty()){
                response.sendRedirect("/error.jsp");
                return;
                //todo 如果不是ajax请求的话是否处理
            }else if (ObjectUtil.isNotNullEmpty(uploadFile) && ajaxMode.isEmpty()){
                String mm="<a style='color:red' href='javascript:void(0)' onclick='showErrmessage()'>上传失败!</a>" +
                        "</br><div style='display:none' id='errDiv'>"+m+"</div>";
                AjaxResponse.sendText(response, StaticParam.getUploadFileFailMessage(mm));
                return;
            }
            else {
               // AjaxSupport.sendFailText("出现错误！",m);
                AjaxSupport.sendFailText(m,"出现错误！");
            }

        }

    }

    public void logger(HttpServletRequest request,Object handler, Exception ex){
        if(ex==null){
            return;
        }
        if (ex instanceof AssertsException){ //如果是断言异常，不处理
            return;
        }
        /*
        if (ex instanceof RedirectAssertsException){ //如果是断言异常，不处理
            return;
        }*/
        StringBuffer msg = new StringBuffer();
        msg.append("异常拦截日志");
        msg.append("[uri＝").append(request.getRequestURI()).append("]");
        Enumeration<String> enumer= request.getParameterNames();
        while (enumer.hasMoreElements()) {
            String name = (String) enumer.nextElement();
            String[] values = request.getParameterValues(name);
            msg.append("[").append(name).append("=");
            if(values != null){
                int i=0;
                for(String value: values){
                    i++;
                    msg.append(value);
                    if(i < values.length){
                        msg.append("｜");
                    }

                }
            }
            msg.append("]");
        }
        log.error(msg,ex);
    }
}
